<template>
  <div 
    :class="[
      'h-full glass-effect border-r flex flex-col sidebar-container transition-all duration-300 ease-in-out',
      isCollapsed ? 'w-16' : 'w-96'
    ]"
    @mouseenter="handleMouseEnter"
    @mouseleave="handleMouseLeave">
    <!-- 折叠/展开按钮 -->
    <div class="p-4 border-b border-glass-border">
      <button 
        @click="toggleCollapse"
        class="glass-button w-full p-3 rounded-lg transition-all duration-200 flex items-center justify-center group"
        :title="isCollapsed ? '展开侧边栏' : '收起侧边栏'">
        <i 
          :class="isCollapsed ? 'fas fa-angle-right' : 'fas fa-angle-left'" 
          class="text-glass-text transition-transform duration-200 group-hover:scale-110">
        </i>
        <span 
          v-if="!isCollapsed" 
          class="ml-2 text-sm font-medium text-glass-text transition-all duration-200 truncate">
          收起侧边栏
        </span>
      </button>
    </div>

    <!-- 顶部用户信息区域 -->
    <div :class="['border-b border-glass-border transition-all duration-300', isCollapsed ? 'p-3' : 'p-6']">
      <div :class="['flex items-center mb-6 transition-all duration-300', isCollapsed ? 'justify-center' : 'space-x-4']">
        <div class="w-12 h-12 glass-card rounded-full flex items-center justify-center relative flex-shrink-0">
          <img 
            v-if="userStore.user?.avatarUrl" 
            :src="userStore.user.avatarUrl" 
            :alt="userStore.user?.username || '用户头像'" 
            class="w-12 h-12 rounded-full object-cover"
            @error="handleAvatarError">
          <div v-else class="w-12 h-12 bg-gradient-to-br from-blue-400 to-purple-500 rounded-full flex items-center justify-center">
            <i class="fas fa-user text-white text-lg"></i>
          </div>
          <!-- 在线状态指示器 -->
          <div class="absolute -bottom-0.5 -right-0.5 w-4 h-4 bg-green-400 rounded-full border-2 border-white shadow-sm"></div>
        </div>
        <div 
          v-if="!isCollapsed" 
          class="flex-1 transition-all duration-300 opacity-100"
          :class="{ 'opacity-0 w-0 overflow-hidden': isCollapsed }">
          <h3 class="font-semibold text-base text-glass-text truncate">
            {{ userStore.user?.username || '未登录用户' }}
          </h3>
          <p class="text-sm text-glass-text-muted flex items-center space-x-1 truncate">
            <i class="fas fa-crown text-amber-500 flex-shrink-0" v-if="userStore.isSubscribed"></i>
            <span class="truncate">{{ userSubscriptionText }}</span>
          </p>
        </div>
        <button 
          v-if="!isCollapsed"
          @click="openSettings" 
          class="glass-button p-3 rounded-lg transition-all duration-300 group flex-shrink-0" 
          title="设置">
          <i class="fas fa-cog text-glass-text-muted group-hover:text-glass-text text-lg transition-colors group-hover:rotate-90 duration-300"></i>
        </button>
      </div>
      
      <!-- 新建对话按钮 -->
      <button 
        @click="createNewChat"
        :disabled="isCreatingChat"
        :class="[
          'glass-button w-full text-glass-text rounded-xl text-lg transition-all duration-200 flex items-center justify-center disabled:opacity-50 disabled:cursor-not-allowed hover:scale-[1.02] active:scale-[0.98]',
          isCollapsed ? 'p-3' : 'py-4 px-6 space-x-3'
        ]"
        :title="isCollapsed ? (isCreatingChat ? '创建中...' : '新建对话') : ''">
        <i :class="isCreatingChat ? 'fas fa-spinner fa-spin' : 'fas fa-plus'" class="text-lg"></i>
        <span 
          v-if="!isCollapsed" 
          class="font-medium transition-all duration-200 truncate">
          {{ isCreatingChat ? '创建中...' : '新建对话' }}
        </span>
      </button>
    </div>

    <!-- 对话历史列表 -->
    <div class="flex-1 overflow-y-auto p-3 custom-scrollbar">
      <!-- 搜索框 -->
      <div 
        v-if="!isCollapsed" 
        class="mb-4 relative transition-all duration-300 opacity-100"
        :class="{ 'opacity-0 pointer-events-none': isCollapsed }">
        <input 
          v-model="searchQuery"
          type="text" 
          placeholder="搜索对话..."
          class="w-full glass-input px-4 py-3 pr-10 rounded-xl text-sm text-glass-text placeholder:text-glass-text-muted"
          @input="handleSearch">
        <i class="fas fa-search absolute right-3 top-1/2 transform -translate-y-1/2 text-glass-text-muted"></i>
      </div>

      <!-- 加载状态 -->
      <div v-if="isLoadingChats" class="flex items-center justify-center py-8">
        <div class="flex items-center space-x-2 text-glass-text-muted">
          <i class="fas fa-spinner fa-spin"></i>
          <span class="text-sm">加载对话中...</span>
        </div>
      </div>

      <!-- 对话列表 -->
      <div v-else class="space-y-2">
        <!-- 折叠状态下的简化显示 -->
        <template v-if="isCollapsed">
          <div class="space-y-2">
            <div 
              v-for="chat in recentChats" 
              :key="chat.id"
              @click="selectChat(chat)"
              :class="[
                'chat-item-collapsed p-3 rounded-lg cursor-pointer transition-all duration-200 group relative flex items-center justify-center',
                selectedChatId === chat.id ? 'sidebar-active-collapsed' : 'hover:bg-glass-bg'
              ]"
              :title="chat.title">
              <i 
                :class="getMessageTypeIcon(chat.lastMessageType)"
                class="text-lg text-glass-text-muted"></i>
            </div>
          </div>
        </template>
        
        <!-- 展开状态下的完整显示 -->
        <template v-else>
          <!-- 分组显示 -->
          <template v-for="group in groupedChats" :key="group.title">
            <div v-if="group.chats.length > 0" class="mb-6 transition-all duration-300">
             <div class="px-4 py-3 text-sm font-medium text-glass-text-muted uppercase tracking-wide truncate">
               {{ group.title }}
             </div>
              
              <div class="space-y-2">
                <div 
                  v-for="chat in group.chats" 
                  :key="chat.id"
                  @click="selectChat(chat)"
                  @contextmenu.prevent="showContextMenu($event, chat)"
                  :class="[
                    'chat-item p-4 rounded-xl cursor-pointer transition-all duration-200 group relative',
                    selectedChatId === chat.id ? 'sidebar-active' : 'hover:bg-glass-bg'
                  ]">
                  <div class="flex items-start justify-between">
                    <div class="flex-1 min-w-0 pr-2">
                      <h4 class="text-base font-medium truncate mb-2 text-glass-text">
                        {{ chat.title || '无标题对话' }}
                      </h4>
                      <p class="text-sm text-glass-text-muted truncate mb-2">
                        {{ chat.lastMessage || '暂无消息' }}
                      </p>
                      <div class="flex items-center justify-between">
                        <span class="text-sm text-glass-text-muted truncate flex-1 mr-2">
                          {{ formatTime(chat.updatedAt) }}
                        </span>
                        <div class="flex items-center space-x-2 flex-shrink-0">
                          <!-- 消息类型图标 -->
                          <i v-if="chat.messageCount > 0" 
                             :class="getMessageTypeIcon(chat.lastMessageType)" 
                             class="text-xs text-glass-text-muted"></i>
                          <!-- 消息数量 -->
                          <span v-if="chat.messageCount > 0" 
                                class="text-xs text-glass-text-muted">
                            {{ chat.messageCount }}
                          </span>
                        </div>
                      </div>
                    </div>
                    <div class="ml-3 opacity-0 group-hover:opacity-100 transition-opacity">
                      <button 
                        @click.stop="showContextMenu($event, chat)"
                        class="p-2 hover:bg-glass-bg-hover rounded text-glass-text-muted hover:text-glass-text transition-colors">
                        <i class="fas fa-ellipsis-v text-sm"></i>
                      </button>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </template>
        </template>

        <!-- 空状态 -->
        <div 
          v-if="filteredChats.length === 0 && !isLoadingChats && !isCollapsed" 
          class="text-center py-12 transition-all duration-300">
          <div class="glass-card w-16 h-16 rounded-full flex items-center justify-center mx-auto mb-4">
            <i class="fas fa-comments text-glass-text-muted text-2xl"></i>
          </div>
          <h3 class="text-lg font-medium text-glass-text mb-2 truncate">
            {{ searchQuery ? '未找到相关对话' : '还没有对话历史' }}
          </h3>
          <p class="text-sm text-glass-text-muted mb-4 truncate">
            {{ searchQuery ? '尝试使用不同的关键词搜索' : '开始您的第一次AI对话吧' }}
          </p>
          <button 
            v-if="!searchQuery"
            @click="createNewChat"
            class="glass-button px-6 py-2 rounded-lg text-sm font-medium">
            立即开始
          </button>
        </div>
      </div>
    </div>

    <!-- 底部功能区域 -->
    <div :class="['border-t border-glass-border space-y-2 transition-all duration-300', isCollapsed ? 'p-2' : 'p-4']">
      <!-- 折叠状态下的简化按钮 -->
      <template v-if="isCollapsed">
        <div class="flex flex-col space-y-2">
          <button 
            @click="viewAllHistory"
            class="w-full flex items-center justify-center p-3 hover:bg-glass-bg rounded-lg transition-colors group"
            title="查看所有历史">
            <i class="fas fa-history text-glass-text-muted group-hover:text-glass-text transition-colors"></i>
          </button>
          
          <button 
            @click="exportChats"
            :disabled="isExporting"
            class="w-full flex items-center justify-center p-3 hover:bg-glass-bg rounded-lg transition-colors group disabled:opacity-50"
            :title="isExporting ? '导出中...' : '导出对话'">
            <i :class="isExporting ? 'fas fa-spinner fa-spin' : 'fas fa-download'" 
               class="text-glass-text-muted group-hover:text-glass-text transition-colors"></i>
          </button>
          
          <button 
            @click="clearAllChats"
            class="w-full flex items-center justify-center p-3 hover:bg-glass-bg rounded-lg transition-colors group"
            title="清空对话">
            <i class="fas fa-trash text-glass-text-muted group-hover:text-red-500 transition-colors"></i>
          </button>
        </div>
      </template>
      
      <!-- 展开状态下的完整按钮 -->
      <template v-else>
        <button 
          @click="viewAllHistory"
          class="w-full flex items-center space-x-3 p-3 hover:bg-glass-bg rounded-lg transition-colors text-left group">
          <i class="fas fa-history text-glass-text-muted group-hover:text-glass-text transition-colors flex-shrink-0"></i>
          <span class="text-sm text-glass-text truncate flex-1">查看所有历史</span>
          <span class="text-xs text-glass-text-muted flex-shrink-0">{{ totalChatsCount }}+</span>
        </button>
        
        <button 
          @click="exportChats"
          :disabled="isExporting"
          class="w-full flex items-center space-x-3 p-3 hover:bg-glass-bg rounded-lg transition-colors text-left group disabled:opacity-50">
          <i :class="isExporting ? 'fas fa-spinner fa-spin' : 'fas fa-download'" 
             class="text-glass-text-muted group-hover:text-glass-text transition-colors flex-shrink-0"></i>
          <span class="text-sm text-glass-text truncate">{{ isExporting ? '导出中...' : '导出对话' }}</span>
        </button>
        
        <button 
          @click="clearAllChats"
          class="w-full flex items-center space-x-3 p-3 hover:bg-glass-bg rounded-lg transition-colors text-left group">
          <i class="fas fa-trash text-glass-text-muted group-hover:text-red-500 transition-colors flex-shrink-0"></i>
          <span class="text-sm text-glass-text group-hover:text-red-500 transition-colors truncate">清空对话</span>
        </button>
      </template>
      
      <div class="pt-2 border-t border-glass-border">
        <!-- 折叠状态下的简化用户区域 -->
        <template v-if="isCollapsed">
          <div class="flex justify-center">
            <button 
              v-if="!userStore.isSubscribed"
              @click="upgradeToPro"
              class="p-3 hover:bg-gradient-to-r hover:from-amber-50 hover:to-yellow-50 rounded-lg transition-all group"
              title="升级到 Pro">
              <i class="fas fa-crown text-amber-500 group-hover:scale-110 transition-transform"></i>
            </button>
            
            <!-- Pro用户显示图标 -->
            <div v-else class="p-3 rounded-lg glass-card hover:scale-105 transition-all duration-200 cursor-pointer" title="Pro 用户 - 本月已使用">
              <i class="fas fa-crown text-amber-500"></i>
            </div>
          </div>
        </template>
        
        <!-- 展开状态下的完整用户区域 -->
        <template v-else>
          <button 
            v-if="!userStore.isSubscribed"
            @click="upgradeToPro"
            class="w-full flex items-center space-x-3 p-3 hover:bg-gradient-to-r hover:from-amber-50 hover:to-yellow-50 rounded-lg transition-all text-left group">
            <i class="fas fa-crown text-amber-500 group-hover:scale-110 transition-transform flex-shrink-0"></i>
            <span class="text-sm text-glass-text font-medium truncate flex-1">升级到 Pro</span>
            <span class="bg-gradient-to-r from-amber-500 to-yellow-500 text-white text-xs px-2 py-1 rounded-full font-medium shadow-sm flex-shrink-0">
              NEW
            </span>
          </button>
          
          <!-- Pro用户显示使用统计 -->
          <div v-else class="glass-card p-3 rounded-lg">
            <div class="flex items-center justify-between mb-2">
              <span class="text-sm font-medium text-glass-text flex items-center truncate flex-1">
                <i class="fas fa-crown text-amber-500 mr-2 flex-shrink-0"></i>
                <span class="truncate">Pro 用户</span>
              </span>
              <span class="text-xs text-glass-text-muted flex-shrink-0">本月</span>
            </div>
            <div class="space-y-1">
              <div class="flex justify-between text-xs">
                <span class="text-glass-text-muted truncate flex-1 mr-2">消息数量</span>
                <span class="text-glass-text font-medium flex-shrink-0">{{ userStats.messageCount || 0 }}</span>
              </div>
              <div class="flex justify-between text-xs">
                <span class="text-glass-text-muted truncate flex-1 mr-2">生成图片</span>
                <span class="text-glass-text font-medium flex-shrink-0">{{ userStats.imageCount || 0 }}</span>
              </div>
            </div>
          </div>
        </template>
      </div>
    </div>

    <!-- 右键菜单 -->
    <div 
      v-if="contextMenu.visible"
      :style="{ top: contextMenu.y + 'px', left: contextMenu.x + 'px' }"
      class="fixed z-[10000] glass-card rounded-lg shadow-2xl border border-glass-border py-2 min-w-48"
      @click.stop>
       <button 
         @click="renameChat(contextMenu.chat)"
         class="w-full flex items-center space-x-3 px-4 py-2 hover:bg-glass-bg-hover text-left transition-colors">
         <i class="fas fa-edit text-glass-text-muted flex-shrink-0"></i>
         <span class="text-sm text-glass-text truncate">重命名</span>
       </button>
       <button 
         @click="pinChat(contextMenu.chat)"
         class="w-full flex items-center space-x-3 px-4 py-2 hover:bg-glass-bg-hover text-left transition-colors">
         <i :class="contextMenu.chat?.isPinned ? 'fas fa-thumbtack text-blue-500' : 'far fa-thumbtack'" class="text-glass-text-muted flex-shrink-0"></i>
         <span class="text-sm text-glass-text truncate">{{ contextMenu.chat?.isPinned ? '取消置顶' : '置顶' }}</span>
       </button>
       <button 
         @click="shareChat(contextMenu.chat)"
         class="w-full flex items-center space-x-3 px-4 py-2 hover:bg-glass-bg-hover text-left transition-colors">
         <i class="fas fa-share text-glass-text-muted flex-shrink-0"></i>
         <span class="text-sm text-glass-text truncate">分享</span>
       </button>
       <div class="border-t border-glass-border my-1"></div>
       <button 
         @click="deleteChat(contextMenu.chat)"
         class="w-full flex items-center space-x-3 px-4 py-2 hover:bg-red-50 text-left transition-colors">
         <i class="fas fa-trash text-red-500 flex-shrink-0"></i>
         <span class="text-sm text-red-500 truncate">删除</span>
       </button>
    </div>

    <!-- 对话框组件 -->
    <div v-if="showDialog" class="fixed inset-0 z-[10001] flex items-center justify-center bg-black bg-opacity-50 backdrop-blur-sm">
      <div class="glass-card p-6 rounded-2xl max-w-md w-full mx-4 shadow-2xl">
        <h3 class="text-lg font-semibold text-glass-text mb-4">{{ dialogConfig?.title }}</h3>
        <p class="text-sm text-glass-text-muted mb-6">{{ dialogConfig?.message }}</p>
        
        <input 
          v-if="dialogConfig?.type === 'input'"
          v-model="dialogInput"
          :placeholder="dialogConfig?.placeholder"
          class="w-full glass-input px-4 py-3 rounded-lg text-sm mb-4"
          @keyup.enter="confirmDialog">
        
        <div class="flex justify-end space-x-3">
          <button 
            @click="cancelDialog"
            class="px-4 py-2 text-sm text-glass-text-muted hover:text-glass-text transition-colors">
            取消
          </button>
          <button 
            @click="confirmDialog"
            :disabled="dialogConfig?.type === 'input' && !dialogInput.trim()"
            class="glass-button px-4 py-2 text-sm font-medium rounded-lg disabled:opacity-50">
            确认
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, watch } from 'vue'
import { useUserStore } from '@/stores/user'

// 定义接口
interface ChatItem {
  id: string
  title: string
  lastMessage: string
  lastMessageType: 'text' | 'image'
  messageCount: number
  isPinned: boolean
  createdAt: string
  updatedAt: string
}

interface UserStats {
  messageCount: number
  imageCount: number
}

interface ContextMenu {
  visible: boolean
  x: number
  y: number
  chat: ChatItem | null
}

interface DialogConfig {
  type: 'confirm' | 'input'
  title: string
  message: string
  placeholder?: string
  onConfirm: () => void
  onCancel?: () => void
}

// Store
const userStore = useUserStore()

// 响应式数据
const chats = ref<ChatItem[]>([])
const selectedChatId = ref<string | null>(null)
const searchQuery = ref('')
const isLoadingChats = ref(true)
const isCreatingChat = ref(false)
const isExporting = ref(false)
const totalChatsCount = ref(0)
const userStats = ref<UserStats>({ messageCount: 0, imageCount: 0 })

// 侧边栏折叠状态
const isCollapsed = ref(false)
const isHovering = ref(false)

// 右键菜单
const contextMenu = ref<ContextMenu>({
  visible: false,
  x: 0,
  y: 0,
  chat: null
})

// 对话框
const showDialog = ref(false)
const dialogConfig = ref<DialogConfig | null>(null)
const dialogInput = ref('')

// 计算属性
const userSubscriptionText = computed(() => {
  if (!userStore.user) return '未登录'
  return userStore.isSubscribed ? 'Pro 用户' : '免费用户'
})

const filteredChats = computed(() => {
  if (!searchQuery.value) return chats.value
  
  const query = searchQuery.value.toLowerCase()
  return chats.value.filter(chat => 
    chat.title.toLowerCase().includes(query) ||
    chat.lastMessage.toLowerCase().includes(query)
  )
})

const groupedChats = computed(() => {
  const groups = [
    { title: '置顶', chats: [] as ChatItem[] },
    { title: '今天', chats: [] as ChatItem[] },
    { title: '昨天', chats: [] as ChatItem[] },
    { title: '本周早些时候', chats: [] as ChatItem[] },
    { title: '更早', chats: [] as ChatItem[] }
  ]

  const now = new Date()
  const today = new Date(now.getFullYear(), now.getMonth(), now.getDate())
  const yesterday = new Date(today.getTime() - 24 * 60 * 60 * 1000)
  const weekAgo = new Date(today.getTime() - 7 * 24 * 60 * 60 * 1000)

  filteredChats.value.forEach(chat => {
    const chatDate = new Date(chat.updatedAt)
    
    if (chat.isPinned) {
      groups[0].chats.push(chat)
    } else if (chatDate >= today) {
      groups[1].chats.push(chat)
    } else if (chatDate >= yesterday) {
      groups[2].chats.push(chat)
    } else if (chatDate >= weekAgo) {
      groups[3].chats.push(chat)
    } else {
      groups[4].chats.push(chat)
    }
  })

  return groups
})

// 折叠状态下显示的最近对话
const recentChats = computed(() => {
  return chats.value.slice(0, 5) // 只显示最近5个对话
})

// API 接口函数
const chatAPI = {
  // 获取对话列表
  async getChats(): Promise<ChatItem[]> {
    try {
      const response = await fetch('/api/chats', {
        headers: {
          'Authorization': userStore.token ? `Bearer ${userStore.token}` : ''
        }
      })
      
      if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`)
      
      const data = await response.json()
      return data.chats || []
    } catch (error) {
      console.error('获取对话列表失败:', error)
      return []
    }
  },

  // 创建新对话
  async createChat(): Promise<ChatItem | null> {
    try {
      const response = await fetch('/api/chats', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': userStore.token ? `Bearer ${userStore.token}` : ''
        },
        body: JSON.stringify({
          title: '新的对话',
          type: 'text'
        })
      })
      
      if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`)
      
      const data = await response.json()
      return data.chat
    } catch (error) {
      console.error('创建对话失败:', error)
      return null
    }
  },

  // 更新对话
  async updateChat(chatId: string, updates: Partial<ChatItem>): Promise<boolean> {
    try {
      const response = await fetch(`/api/chats/${chatId}`, {
        method: 'PATCH',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': userStore.token ? `Bearer ${userStore.token}` : ''
        },
        body: JSON.stringify(updates)
      })
      
      return response.ok
    } catch (error) {
      console.error('更新对话失败:', error)
      return false
    }
  },

  // 删除对话
  async deleteChat(chatId: string): Promise<boolean> {
    try {
      const response = await fetch(`/api/chats/${chatId}`, {
        method: 'DELETE',
        headers: {
          'Authorization': userStore.token ? `Bearer ${userStore.token}` : ''
        }
      })
      
      return response.ok
    } catch (error) {
      console.error('删除对话失败:', error)
      return false
    }
  },

  // 导出对话
  async exportChats(): Promise<Blob | null> {
    try {
      const response = await fetch('/api/chats/export', {
        headers: {
          'Authorization': userStore.token ? `Bearer ${userStore.token}` : ''
        }
      })
      
      if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`)
      
      return await response.blob()
    } catch (error) {
      console.error('导出对话失败:', error)
      return null
    }
  },

  // 获取用户统计
  async getUserStats(): Promise<UserStats> {
    try {
      const response = await fetch('/api/user/stats', {
        headers: {
          'Authorization': userStore.token ? `Bearer ${userStore.token}` : ''
        }
      })
      
      if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`)
      
      const data = await response.json()
      return data.stats || { messageCount: 0, imageCount: 0 }
    } catch (error) {
      console.error('获取用户统计失败:', error)
      return { messageCount: 0, imageCount: 0 }
    }
  }
}

// 方法
const loadChats = async () => {
  isLoadingChats.value = true
  try {
    const [chatsData, statsData] = await Promise.all([
      chatAPI.getChats(),
      chatAPI.getUserStats()
    ])
    
    chats.value = chatsData
    userStats.value = statsData
    totalChatsCount.value = chatsData.length
  } catch (error) {
    console.error('加载数据失败:', error)
  } finally {
    isLoadingChats.value = false
  }
}

const createNewChat = async () => {
  if (isCreatingChat.value) return
  
  isCreatingChat.value = true
  try {
    const newChat = await chatAPI.createChat()
    if (newChat) {
      chats.value.unshift(newChat)
      selectedChatId.value = newChat.id
      // 触发事件通知父组件
      emit('chat-selected', newChat)
    }
  } catch (error) {
    console.error('创建对话失败:', error)
  } finally {
    isCreatingChat.value = false
  }
}

const selectChat = (chat: ChatItem) => {
  selectedChatId.value = chat.id
  emit('chat-selected', chat)
}

const showContextMenu = (event: MouseEvent, chat: ChatItem) => {
  event.preventDefault()
  contextMenu.value = {
    visible: true,
    x: event.clientX,
    y: event.clientY,
    chat
  }
}

const hideContextMenu = () => {
  contextMenu.value.visible = false
}

const showDialogHelper = (config: DialogConfig) => {
  dialogConfig.value = config
  showDialog.value = true
  dialogInput.value = ''
}

const confirmDialog = () => {
  if (dialogConfig.value?.onConfirm) {
    dialogConfig.value.onConfirm()
  }
  showDialog.value = false
}

const cancelDialog = () => {
  if (dialogConfig.value?.onCancel) {
    dialogConfig.value.onCancel()
  }
  showDialog.value = false
}

const renameChat = (chat: ChatItem | null) => {
  if (!chat) return
  
  showDialogHelper({
    type: 'input',
    title: '重命名对话',
    message: '请输入新的对话名称',
    placeholder: chat.title,
    onConfirm: async () => {
      const newTitle = dialogInput.value.trim()
      if (newTitle && newTitle !== chat.title) {
        const success = await chatAPI.updateChat(chat.id, { title: newTitle })
        if (success) {
          chat.title = newTitle
        }
      }
    }
  })
  
  hideContextMenu()
}

const pinChat = async (chat: ChatItem | null) => {
  if (!chat) return
  
  const success = await chatAPI.updateChat(chat.id, { isPinned: !chat.isPinned })
  if (success) {
    chat.isPinned = !chat.isPinned
  }
  
  hideContextMenu()
}

const shareChat = (chat: ChatItem | null) => {
  if (!chat) return
  
  // 生成分享链接
  const shareUrl = `${window.location.origin}/share/${chat.id}`
  navigator.clipboard.writeText(shareUrl)
  
  showDialogHelper({
    type: 'confirm',
    title: '分享对话',
    message: '分享链接已复制到剪贴板！',
    onConfirm: () => {}
  })
  
  hideContextMenu()
}

const deleteChat = (chat: ChatItem | null) => {
  if (!chat) return
  
  showDialogHelper({
    type: 'confirm',
    title: '删除对话',
    message: `确定要删除"${chat.title}"吗？此操作无法撤销。`,
    onConfirm: async () => {
      const success = await chatAPI.deleteChat(chat.id)
      if (success) {
        const index = chats.value.findIndex(c => c.id === chat.id)
        if (index !== -1) {
          chats.value.splice(index, 1)
        }
        if (selectedChatId.value === chat.id) {
          selectedChatId.value = null
          emit('chat-selected', null)
        }
      }
    }
  })
  
  hideContextMenu()
}

const exportChats = async () => {
  if (isExporting.value) return
  
  isExporting.value = true
  try {
    const blob = await chatAPI.exportChats()
    if (blob) {
      const url = URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = url
      a.download = `chat-history-${new Date().toISOString().split('T')[0]}.json`
      document.body.appendChild(a)
      a.click()
      document.body.removeChild(a)
      URL.revokeObjectURL(url)
    }
  } catch (error) {
    console.error('导出失败:', error)
  } finally {
    isExporting.value = false
  }
}

const clearAllChats = () => {
  showDialogHelper({
    type: 'confirm',
    title: '清空所有对话',
    message: '确定要清空所有对话历史吗？此操作无法撤销。',
    onConfirm: async () => {
      // 批量删除所有对话
      const deletePromises = chats.value.map(chat => chatAPI.deleteChat(chat.id))
      const results = await Promise.allSettled(deletePromises)
      
      // 只保留删除失败的对话
      const failedChats = chats.value.filter((_, index) => 
        results[index].status === 'rejected'
      )
      
      chats.value = failedChats
      selectedChatId.value = null
      emit('chat-selected', null)
    }
  })
}

const viewAllHistory = () => {
  emit('view-all-history')
}

const upgradeToPro = () => {
  emit('upgrade-to-pro')
}

const openSettings = () => {
  emit('open-settings')
}

const handleSearch = () => {
  // 搜索逻辑已在计算属性中处理
}

// 折叠/展开相关方法
const toggleCollapse = () => {
  isCollapsed.value = !isCollapsed.value
  // 保存折叠状态到localStorage
  localStorage.setItem('sidebarCollapsed', isCollapsed.value.toString())
  
  // 当折叠时清空搜索
  if (isCollapsed.value) {
    searchQuery.value = ''
  }
  
  // 通知父组件折叠状态变化
  emit('collapse-changed', isCollapsed.value)
}

const handleMouseEnter = () => {
  isHovering.value = true
}

const handleMouseLeave = () => {
  isHovering.value = false
}

const handleAvatarError = (event: Event) => {
  const img = event.target as HTMLImageElement
  img.style.display = 'none'
}

const formatTime = (dateString: string) => {
  const date = new Date(dateString)
  const now = new Date()
  const diffInHours = (now.getTime() - date.getTime()) / (1000 * 60 * 60)
  
  if (diffInHours < 1) {
    return Math.floor(diffInHours * 60) + '分钟前'
  } else if (diffInHours < 24) {
    return Math.floor(diffInHours) + '小时前'
  } else if (diffInHours < 48) {
    return '昨天 ' + date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
  } else {
    return date.toLocaleDateString('zh-CN', { month: '2-digit', day: '2-digit' })
  }
}

const getMessageTypeIcon = (type: string) => {
  switch (type) {
    case 'image':
      return 'fas fa-image'
    case 'text':
    default:
      return 'fas fa-comment-dots'
  }
}

// 事件
const emit = defineEmits<{
  'chat-selected': [chat: ChatItem | null]
  'view-all-history': []
  'upgrade-to-pro': []
  'open-settings': []
  'collapse-changed': [collapsed: boolean]
}>()

// 生命周期
onMounted(() => {
  // 恢复折叠状态
  const savedCollapsedState = localStorage.getItem('sidebarCollapsed')
  if (savedCollapsedState !== null) {
    isCollapsed.value = savedCollapsedState === 'true'
    // 初始化时也要通知父组件
    emit('collapse-changed', isCollapsed.value)
  }
  
  loadChats()
  document.addEventListener('click', hideContextMenu)
})

onUnmounted(() => {
  document.removeEventListener('click', hideContextMenu)
})

// 监听用户登录状态变化
watch(() => userStore.isAuthenticated, (newValue) => {
  if (newValue) {
    loadChats()
  } else {
    chats.value = []
    selectedChatId.value = null
  }
})
</script>

<style scoped>
.sidebar-container {
  /* 自定义滚动条 */
}

.custom-scrollbar::-webkit-scrollbar {
  width: 6px;
}

.custom-scrollbar::-webkit-scrollbar-track {
  background: transparent;
}

.custom-scrollbar::-webkit-scrollbar-thumb {
  background-color: rgba(0, 0, 0, 0.1);
  border-radius: 3px;
}

.custom-scrollbar::-webkit-scrollbar-thumb:hover {
  background-color: rgba(0, 0, 0, 0.2);
}

.sidebar-active {
  background: rgba(0, 0, 0, 0.05);
  border-left: 3px solid #000000;
}

.chat-item:hover {
  background: rgba(0, 0, 0, 0.03);
}

.glass-input {
  background: rgba(255, 255, 255, 0.8);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(0, 0, 0, 0.1);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.glass-input:focus {
  background: rgba(255, 255, 255, 0.95);
  border-color: rgba(0, 0, 0, 0.2);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  outline: none;
}

/* 动画效果 */
@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.chat-item {
  animation: fadeIn 0.3s ease-out;
}

/* 设置按钮旋转动画 */
.group:hover .fa-cog {
  transform: rotate(90deg);
}

/* 高级毛玻璃效果 */
.glass-effect {
  background: linear-gradient(135deg, rgba(255, 255, 255, 0.9) 0%, rgba(255, 255, 255, 0.8) 100%);
  backdrop-filter: blur(25px) saturate(1.8);
  border: 1px solid rgba(255, 255, 255, 0.2);
  box-shadow: 
    0 8px 32px rgba(0, 0, 0, 0.1),
    0 4px 16px rgba(0, 0, 0, 0.05),
    inset 0 1px 0 rgba(255, 255, 255, 0.5);
}

.glass-card {
  background: linear-gradient(135deg, rgba(255, 255, 255, 0.95) 0%, rgba(255, 255, 255, 0.85) 100%);
  backdrop-filter: blur(20px) saturate(1.5);
  border: 1px solid rgba(255, 255, 255, 0.3);
  box-shadow: 
    0 6px 24px rgba(0, 0, 0, 0.1),
    0 3px 12px rgba(0, 0, 0, 0.05),
    inset 0 1px 0 rgba(255, 255, 255, 0.6);
}

.glass-button {
  background: linear-gradient(135deg, rgba(255, 255, 255, 0.9) 0%, rgba(255, 255, 255, 0.7) 100%);
  backdrop-filter: blur(15px) saturate(1.5);
  border: 1px solid rgba(255, 255, 255, 0.3);
  box-shadow: 
    0 4px 16px rgba(0, 0, 0, 0.08),
    inset 0 1px 0 rgba(255, 255, 255, 0.6);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.glass-button:hover:not(:disabled) {
  background: linear-gradient(135deg, rgba(255, 255, 255, 0.95) 0%, rgba(255, 255, 255, 0.8) 100%);
  transform: translateY(-1px);
  box-shadow: 
    0 6px 20px rgba(0, 0, 0, 0.12),
    inset 0 1px 0 rgba(255, 255, 255, 0.8);
}

.glass-button:active:not(:disabled) {
  transform: translateY(0);
}

/* 折叠状态样式 */
.chat-item-collapsed {
  background: rgba(255, 255, 255, 0.6);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(0, 0, 0, 0.05);
  transition: all 0.2s ease;
}

.chat-item-collapsed:hover {
  background: rgba(255, 255, 255, 0.8);
  transform: scale(1.05);
}

.sidebar-active-collapsed {
  background: rgba(0, 0, 0, 0.1) !important;
  border: 2px solid #000000;
}

/* 折叠动画 */
.sidebar-container {
  overflow: hidden;
}

/* 文本淡入淡出动画 */
@keyframes fadeInScale {
  from {
    opacity: 0;
    transform: scale(0.95);
  }
  to {
    opacity: 1;
    transform: scale(1);
  }
}

@keyframes fadeOutScale {
  from {
    opacity: 1;
    transform: scale(1);
  }
  to {
    opacity: 0;
    transform: scale(0.95);
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .sidebar-container {
    width: 100% !important;
    max-width: 320px;
  }
}
</style>
